package oop.ex3.sharedclasses;
// TODO check package


/**
 * Represent an IP+Port address.
 * Contains the address's IP as a String,
 * and the Port as an integer.
 * @author zablo
 *
 */
public class IPaddress{
	
	private String _ip;
	private int _port;
	
	private static final char ADDRESS_PARAMETER_SPACER='%';
	private static final int IP_START_INDEX=0;
	
	/**
	 * Basic Constructor: null IP & port = 0.
	 * 
	 */
	public IPaddress(){
		this._ip=null;
		this._port=0;
	}
	
	/**
	 * Constructs a new IPaddress object.
	 * @param ip the address's IP.
	 * @param port the address's Port.
	 */
	public IPaddress(String ip, int port){
		this._ip=ip;
		this._port=port;
	}
	
	/**
	 * Copy constructor: constructs a new IPaddress from an existing one.
	 * @param ipAddress the IPaddress to be copied.
	 */
	public IPaddress(IPaddress ipAddress){
		this._ip=ipAddress._ip;
		this._port=ipAddress._port;
	}
	
	/**
	 * Returns the IPaddress's IP.
	 * @return the IPaddress's IP.
	 */
	public String getIP(){
		return this._ip;
	}
	
	/**
	 * Returns the IPaddress's Port.
	 * @return the IPaddress's Port.
	 */
	public int getPort(){
		return this._port;
	}
	
	/**
	 * Sets new values for the IPaddress's IP & Port.
	 * @param ip the new IP.
	 * @param port the new Port.
	 */
	public void setIPAndPort(String ip, int port){
		this._ip=ip;
		this._port=port;
	}
	
	//TODO check if compareTo is needed or not
	/**
	 * Checks in two IPaddresses are equals or not.
	 * @param other the IPaddress to be compared to.
	 * @return true if indeed equal, false otherwise.
	 */
	public boolean equals(IPaddress other){
		if (this._ip.equals(other._ip) && this._port==other._port){
			return true;
		}
		return false;
	}
	
	//TODO delete toString
	public String toString(){
		return this._ip+"%"+this._port;
	}

	/**
	 * Interprets an IPaddress from a String.
	 * assuming the String is of pattern : xxx.xxx.xxx.xxx%port,
	 * Will create a new IPaddress with IP: xxx.xxx.xxx.xxx and PORT: port.
	 * @param inputLine the String to be interpreted.
	 * @return a new IPaddress with the interpreted IP and PORT.
	 */
	public static IPaddress interpretLine(String inputLine) {
		int spacerIndex = inputLine.indexOf(ADDRESS_PARAMETER_SPACER);
		String ip = inputLine.substring(IP_START_INDEX, spacerIndex);
		int port = Integer.parseInt(inputLine.substring(ADDRESS_PARAMETER_SPACER+1));
		
		return new IPaddress(ip, port);
	}
}